<template>
  <PopupCpt ref="refPopupCpt">
    <template #default>
      <van-sticky>
        <van-nav-bar title="详情" left-text="" left-arrow @click-left="close" />
      </van-sticky>
      <!-- 内容 -->
      <div class="handle-content">
        <!-- 内容信息 -->
        <div class="title">
          温馨提示：这是评估您近期的心理状态，可能会受到特殊事件和当前心境的影响，此测试结果仅供参考!
        </div>
        <div>
          <van-collapse v-model="activeNames">
            <!-- 遍历模块信息 -->
            <van-collapse-item
              v-for="item of infoTypes"
              :key="item['key']"
              :name="item['key']"
              :title="item['label']"
            >
              <van-cell-group inset>
                <van-row>
                  <van-col
                    v-for="col of getColumns(item['key'])"
                    :key="col['field']"
                    :span="col['span']"
                  >
                    <van-field
                      :label="col['label']"
                      colon
                      :label-width="col['labelWidth']"
                    >
                      <template #input>{{
                        (item['key'] === 'userInfo' ? userData : otherData)[
                          col['field']
                        ]
                      }}</template>
                    </van-field>
                  </van-col>
                </van-row>
              </van-cell-group>
            </van-collapse-item>
            <!-- 预警信息-特殊处理 -->
            <Warn
              v-if="hdType === 'warn' && warnList && warnList.length"
              ref="refWarn"
              :warn-list="warnList"
              :hd-edit="hdEdit"
              :hd-row-data="hdRowData"
            >
            </Warn>
            <!-- 处理意见 -->
            <van-collapse-item name="handleOpinions" title="处理意见">
              <van-form
                ref="refSubmitForm"
                :readonly="!hdEdit"
                @submit="submitOpinions"
              >
                <van-cell-group inset>
                  <van-row>
                    <van-col span="24">
                      <van-field
                        v-model="submitForm.handleOpinions"
                        type="textarea"
                        colon
                        show-word-limit
                        autosize
                        required
                        :readonly="!hdEdit"
                        name="handleOpinions"
                        :rules="
                          hdEdit
                            ? [{ required: true, message: '请输入处理意见' }]
                            : []
                        "
                        maxlength="2000"
                        placeholder="最大支持2000字"
                      />
                    </van-col>
                  </van-row>
                </van-cell-group>
                <div v-if="hdEdit" class="btns">
                  <van-button
                    round
                    block
                    size="small"
                    type="primary"
                    :disabled="apis.submit.status === 1"
                    :loading="apis.submit.status === 1"
                    native-type="submit"
                    >提 交</van-button
                  >
                </div>
              </van-form>
            </van-collapse-item>
          </van-collapse>
        </div>
      </div>
    </template>
  </PopupCpt>
</template>

<script lang="ts">
import axios from '/@/api/axios'
import PopupCpt from '/@/components/PopupCpt.vue'
import Warn from './warn.vue'
import { getUserInfo } from '/@/util/business-util'
import { allInfoTypes, getInfoTypesByType, getColumns, getUrl } from './config'
import { Toast } from 'vant'
import { useStore } from '/@/store'
import { defineComponent, ref } from 'vue'

export default defineComponent({
  components: { PopupCpt, Warn },
  props: {
    allGradeInfo: Array, // 所有年级
  },
  setup(props, _context) {
    const { commit, state } = useStore()
    const allGradeInfo = props.allGradeInfo
    let refPopupCpt: any = ref(null) // 弹出框的$refs值
    let refWarn: any = ref(null) // 预警模块的$refs值
    let refSubmitForm: any = ref(null) // 提交表单的$refs值
    let hdType: any = ref('') // 类型，warn=预警等
    let hdRowData: any = ref({}) // 当前类型处理的数据
    let hdEdit: any = ref(false) // 当前类型是否编辑的状态
    let userData: any = ref({}) // 当前处理的学生信息
    let otherData: any = ref({}) // 当前处理的其他信息
    let baseData: any = ref({})
    let infoTypes: any = ref([])
    let warnList: any = ref([]) // 预警信息
    // 待提交的表单
    let submitForm = ref({
      handleOpinions: '', // 处理意见
    })
    // 接口请求url、请求状态、参数等信息
    let apis: any = ref({})
    // 调用保存类接口
    async function callSaveApi(
      apiOp: {
        status: number
        url: string
        type: string
        getParams: Function | null
      },
      params: any,
      callback: Function | null // 成功的回调
    ) {
      console.log('callSaveApi', JSON.stringify(params))
      if (typeof apiOp['getParams'] === 'function') {
        params = await apiOp['getParams'](params)
      }
      apiOp['status'] = 1 // 请求中
      let res = await axios[apiOp['type']](apiOp['url'], params)
      if (res.status === 200) {
        // 请求成功
        if (typeof callback === 'function') {
          callback(params)
        }
      }
      apiOp['status'] = 0 // 恢复未请求状态
    }
    // 获取/设置当前要处理的学生信息
    async function initCurUserInfo(rowData: any) {
      userData.value =
        (await getUserInfo(commit, state, rowData.userId, false)) || {}
      Object.assign(userData.value, baseData.value)
    }
    // 获取/设置当前要处理的预约/预警信息
    async function initCurOtherInfo(type: string, rowData: any) {
      // 预警
      if (type === 'warn') {
        let { data } = await axios.get(
          `/api/blade-measure/measure/report/findPersonalInfo?id=${rowData.userProjectGaugeId}`
        )
        data = data.data || {}
        hdRowData.value.gaugeName = data.gaugeName || ''
        console.log(hdRowData)
        baseData.value = {
          gradeName: data.gradeName || '',
        }
        Object.assign(userData.value, baseData.value)
        // 获取预警信息
        warnList.value = data.factorList || []
        submitForm.value.handleOpinions = data.coachDecs || ''
      }
    }
    function initApis(handleType: string, handleRowData: any) {
      apis.value = {
        // 提交意见接口
        submit: {
          url: getUrl(handleType, 'submit'),
          type: 'post', // 接口请求类型
          status: 0, // 接口请求状态，0=未请求，1=请求中
          async getParams(params: any) {
            if (handleType === 'warn') {
              return params
            }
            let id = handleRowData.id
            // 参数
            return {
              id: id,
              coachDecs: params.handleOpinions,
            }
          },
        },
        // 报错草稿意见接口
        saveDraft: {
          url: '',
          type: 'post', // 接口请求类型
          status: 0, // 接口请求状态，0=未请求，1=请求中
          async getParams(params: any) {
            // 参数
            return params
          },
        },
      }
    }
    // 显示
    function show(type: string, rowData: any, isEdit: boolean) {
      _context.emit('show', _context) // 触发事件
      refPopupCpt.value.show()
      hdType.value = type
      hdRowData.value = rowData
      hdEdit.value = !!isEdit
      initCurUserInfo(rowData) // 异步获取/设置学生信息
      initApis(type, rowData) // 初始化接口设置
      initCurOtherInfo(type, rowData) // 获取/设置当前要处理的预约/预警信息
      infoTypes.value = getInfoTypesByType(type)
    }
    // 隐藏
    function close() {
      refSubmitForm.value.resetValidation() // 清理表单的错误提示
      _context.emit('close', _context) // 触发事件
      refPopupCpt.value.close()
    }
    return {
      refPopupCpt,
      refWarn,
      refSubmitForm,
      hdType,
      hdRowData,
      hdEdit,
      userData,
      otherData,
      apis,
      submitForm,
      show,
      close,
      getColumns,
      infoTypes,
      initCurUserInfo,
      warnList,
      // 提交意见
      async submitOpinions(stData: { handleOpinions: string }) {
        let params = stData
        // 预警
        if (hdType.value === 'warn') {
          params = await refWarn.value.getData()
          if (!params) {
            return
          }
          Object.assign(params, { coachDecs: stData.handleOpinions })
        }
        callSaveApi(apis.value.submit, params, () => {
          // 成功的回调
          Toast('提交成功！')
          close()
          _context.emit('submitSuccess', _context) // 触发事件
        })
      },
      // 保存草稿意见
      async saveDraftOpinions() {
        callSaveApi(apis.value.saveDraft, submitForm.value, () => {
          // 成功的回调
          Toast('保存成功！')
          close()
        })
      },
    }
  },
  data() {
    return {
      // 默认显示全部折叠面板
      activeNames: allInfoTypes
        .map((it: { key: string }) => it['key'])
        .concat(['handleOpinions']),
    }
  },
})
</script>

<style lang="less">
.handle-content {
  .van-cell {
    padding-bottom: 5px;
    &::after {
      border-bottom: 0;
    }
  }

  .van-cell-group .van-row,
  .van-cell-group .van-cell.van-field {
    background-color: #f5f7f9;
    padding: 4px;
  }

  .van-cell-group--inset {
    margin: 0;
  }

  .btns {
    margin: 30px 10px 20px;
    text-align: center;
  }

  .din-inset-group {
    margin-bottom: 20px !important;
  }
}

.title {
  color: #4994df;
  font-size: 14px;
  padding: 5px 15px;
}
</style>
